package com.dizner.androidcartest;

import android.util.Log;

import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManager;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class HWSensor implements AutoCloseable {

    private static final String TAG = HWSensor.class.getSimpleName();
    private Gpio seneorOutPin;
    private PeripheralManager mPm;
    private String sensorName;
    private boolean isClosed;
    private Thread sensorRunThread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isClosed) {
                    try {
                        boolean value = seneorOutPin.getValue();
//                        Log.i(TAG, "障碍：" + !value);
                        if (listenerList != null && listenerList.size() > 0) {
                            for (OnHWSensorHasDataListener dataListener : listenerList) {
                                if (dataListener != null) {
                                    dataListener.onHasData(sensorName, !value);
                                }
                            }
                            TimeUnit.MILLISECONDS.sleep(1000);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    public static HWSensor getInstance(String gpioName, String sensorName) {
        return new HWSensor(gpioName, sensorName);
    }

    private HWSensor(final String gpioName, final String sensorName) {
        mPm = PeripheralManager.getInstance();
        this.sensorName = sensorName;
        try {
            seneorOutPin = mPm.openGpio(gpioName);
            seneorOutPin.setDirection(Gpio.DIRECTION_IN);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void run() {
        if (sensorRunThread != null && !sensorRunThread.isAlive()) {
            sensorRunThread.start();
        }

    }

    private List<OnHWSensorHasDataListener> listenerList;


    public HWSensor register(OnHWSensorHasDataListener... listener) {
        if (listenerList == null) {
            listenerList = new ArrayList<>();
        }
        listenerList.addAll(Arrays.asList(listener));
//        this.listener = listener;
        return this;
    }

    interface OnHWSensorHasDataListener {
        void onHasData(String sensorName, boolean hasZA);
    }

    @Override
    public void close() throws Exception {
        isClosed = true;
    }
}
